using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;

namespace BanZuiCloudControlAgent.Core.Mqtt
{
    /// <summary>
    /// MQTT客户端配置选项
    /// </summary>
    public class MqttClientOptions
    {
        /// <summary>
        /// 服务器地址
        /// </summary>
        public string ServerUrl { get; set; }

        /// <summary>
        /// 服务器端口
        /// </summary>
        public int ServerPort { get; set; }

        /// <summary>
        /// 用户名
        /// </summary>
        public string Username { get; set; }

        /// <summary>
        /// 密码
        /// </summary>
        public string Password { get; set; }

        /// <summary>
        /// 客户端ID
        /// </summary>
        public string ClientId { get; set; }

        /// <summary>
        /// 设备码，从用户名中提取
        /// </summary>
        public string DeviceCode { get; private set; }

        /// <summary>
        /// 是否使用TLS
        /// </summary>
        public bool UseTls { get; set; }

        /// <summary>
        /// 是否允许不受信任的证书
        /// </summary>
        public bool AllowUntrustedCertificates { get; set; }

        /// <summary>
        /// 心跳间隔（秒）
        /// </summary>
        public int KeepAliveInterval { get; set; }

        /// <summary>
        /// 是否使用清理会话
        /// </summary>
        public bool CleanSession { get; set; }

        /// <summary>
        /// 会话过期时间（秒）
        /// </summary>
        public int SessionExpiryInterval { get; set; }

        /// <summary>
        /// 自动重连延迟（秒）
        /// </summary>
        public int AutoReconnectDelay { get; set; }

        /// <summary>
        /// 最大重连尝试次数，0表示无限次
        /// </summary>
        public int MaxReconnectAttempts { get; set; }

        /// <summary>
        /// 主题前缀
        /// </summary>
        public string TopicPrefix { get; set; }

        /// <summary>
        /// 构造函数，使用默认值初始化
        /// </summary>
        public MqttClientOptions()
        {
            ServerUrl = "localhost";
            ServerPort = 1883;
            Username = string.Empty;
            Password = string.Empty;
            ClientId = string.Empty;
            DeviceCode = string.Empty;
            UseTls = false;
            AllowUntrustedCertificates = false;
            KeepAliveInterval = 60;
            CleanSession = false;
            SessionExpiryInterval = 7200; // 2小时
            AutoReconnectDelay = 5;
            MaxReconnectAttempts = 0; // 无限次
            TopicPrefix = "cloud";
        }

        /// <summary>
        /// 从配置中加载MQTT客户端选项
        /// </summary>
        /// <returns>MQTT客户端选项</returns>
        public static MqttClientOptions FromConfig()
        {
            var uiSettings = Utils.Common.ConfigurationManager.UI;
            
            // 优先使用配置中的DeviceCode，如果为空则从用户名中提取
            string deviceCode = uiSettings.DeviceCode;
            if (string.IsNullOrEmpty(deviceCode))
            {
                deviceCode = ExtractDeviceCodeFromUsername(uiSettings.Username);
            }
            
            return new MqttClientOptions
            {
                ServerUrl = uiSettings.ServerUrl,
                ServerPort = uiSettings.ServerPort,
                Username = uiSettings.Username,
                Password = uiSettings.Password,
                ClientId = uiSettings.Username,
                DeviceCode = deviceCode, 
                UseTls = uiSettings.UseTls,
                AllowUntrustedCertificates = false,
                KeepAliveInterval = uiSettings.HeartbeatInterval,
                CleanSession = false,
                SessionExpiryInterval = 7200, // 2小时
                AutoReconnectDelay = uiSettings.ReLoginInterval,
                MaxReconnectAttempts = uiSettings.MaxReLoginAttempts,
                TopicPrefix = uiSettings.TopicPrefix
            };
        }

        /// <summary>
        /// 从用户名中提取设备码
        /// </summary>
        /// <param name="username">用户名</param>
        /// <returns>设备码</returns>
        public static string ExtractDeviceCodeFromUsername(string username)
        {
            if (string.IsNullOrEmpty(username))
            {
                return string.Empty;
            }
            
            // 检查是否包含下划线，如果有则提取下划线后面的部分
            if (username.Contains("_"))
            {
                string[] parts = username.Split('_');
                if (parts.Length > 1 && !string.IsNullOrEmpty(parts[1]))
                {
                    return parts[1];
                }
            }
            
            // 检查整个用户名是否为数字
            if (username.All(char.IsDigit))
            {
                return username;
            }
            
            // 提取用户名中的所有数字
            string numbers = new string(username.Where(char.IsDigit).ToArray());
            if (!string.IsNullOrEmpty(numbers))
            {
                return numbers;
            }
            
            // 如果无法提取，则返回原始用户名
            return username;
        }

        /// <summary>
        /// 生成随机客户端ID
        /// </summary>
        /// <param name="deviceCode">设备码</param>
        /// <returns>随机客户端ID</returns>
        public static string GenerateClientId(string deviceCode)
        {
            return $"device_{deviceCode}_{Guid.NewGuid().ToString().Substring(0, 8)}";
        }
    }
} 